localStorage.setItem('x-token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaW5mbyI6eyJpZCI6IjEiLCJsb2dpbl9uYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6Ijk2ZTc5MjE4OTY1ZWI3MmM5MmE1NDlkZDVhMzMwMTEyIiwibmFtZSI6IlRoaW5rSlPkuIDlk6UiLCJlbWFpbCI6Imhld3UxMTIyQDE2My5jb20iLCJwaG9uZSI6IjE3MzQyMDY1OTA5IiwibG9naW5faXAiOiI6OjEiLCJsb2dpbl9kYXRlIjoiMjAxOC0wMS0wOCAxNjoyMjo1MSIsImNyZWF0ZV9kYXRlIjoiMjAxNy0xMi0xNCAxMTo1Mjo0NiIsInVwZGF0ZV9kYXRlIjoiMjAyMy0wNi0xNSAwNzo1ODo1OCIsImRlbF9mbGFnIjoiMCIsInJvbGVfaWQiOlsiMWM1NGUwMDNjMWZjNGRjZDliMDg3ZWY4ZDQ4YWJhYzMiXSwic3RhdHVzIjoxLCJkZWZhdWx0X2RhdGEiOiIxIiwicm9sZW5hbWUiOlsi6LaF57qn566h55CG5ZGYIl19LCJpYXQiOjE2ODY5NzIyNzl9.xl_rD0eBqXMPaEZjjmhS51vkkmm_KwROJvYYNf1GUDQ')

// 把参数放到一个对象
const query = {
  catename: '',	//	分类名称
  page: 1,  	  //	页码
  limit: 5,	    //	每页数量
}

// 渲染
async function render() {
  const { data: { data } } = await axios.get('/ydd_cate/list', { params: query })
  // console.log(data)
  const res = data.data
  // console.log(res);
  // console.log(res.icon)

  document.querySelector('#list').innerHTML = res.map(({ catename, icon, sort_num, id }, index) => {
    return `
            <tr>
                <td >${index + 1}</td>
                <td name="one">${id}</td>
                <td name="two">${catename}</td>
                <td name="three">${icon} <i class="fa ${icon}"></i> </td>
                <td name="four">${sort_num}</td>
                <td>
                   <button type="button"
                    class="layui-btn layui-btn-xs btn_edit layui-icon layui-icon-edit wxy_edit wxy_add_del" data-id="${id}"></button>
                   <button type="button"
                    class="layui-btn layui-btn-danger layui-btn-xs btn_delete layui-icon layui-icon-delete wxy_del wxy_add_del" data-id="${id}"></button>
                </td>
            </tr>
        `
  }).join('')

  // //  在这渲染分页，因为在这获取可以到总数
  renderPage(data.count)
}
render()

// todo ================= 添加分类功能 =================================
// 弹出模态框
const addFormstr = `
          <form id="addForm" class="layui-form">
            <!-- 第一行 分类名称 -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类名称</label>
              <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required" placeholder="请输入分类名" autocomplete="off"
                  class="layui-input wxy_fenlei">
              </div>
            </div>
            <!-- 第二行 分类图标  -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类图标</label>
              <div class="layui-input-block wxy_fot">
                <input type="text" name="alias" required lay-verify="required" placeholder="请输入class名" autocomplete="off"
                  class="layui-input" style="width: 50%;">
              </div>
            </div>
            <!-- 第三行 -->
            <div class="layui-form-item">
              <label class="layui-form-label">排序大小</label>
              <div class="layui-input-block wxy_jiajian">
                <span class="wxy_jia j_j">+</span>
                <input type="text" name="alias" required lay-verify="required" placeholder="" autocomplete="off"
                  class="layui-input zj" style="width: 30%;">
                <span class="wxy_jian j_j">-</span>
              </div>
            </div>
            <!-- 第四行 按钮 -->
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button class="layui-btn form_add" lay-submit lay-filter="formDemo">确认添加</button>
                <button type="reset" class="layui-btn layui-btn-primary" id="form_reset">重置</button>
              </div>
            </div>
          </form>
`
let indexADdForm
document.querySelector('#newly').addEventListener('click', function () {
  indexADdForm = layer.open({
    content: addFormstr,
    type: 1,
    title: ['添加分类', 'font-size:18px;'],
    area: ['684px', '347px']
  })
})

// 点击提交
// 事件委托给body
document.querySelector('body').addEventListener('click', async function (e) {
  e.preventDefault()

  const form = document.querySelector('#addForm')
  // 如果点击添加
  // 收集表单数据
  if (e.target.className === 'layui-btn form_add') {
    const { alias, name } = serialize(form, { hash: true })
    const catename = name
    const sort_num = alias[1]
    const icon = alias[0]
    // console.log(name)
    // console.log(sort_num)
    // console.log(icon);

    // 发送ajax请求
    try {
      const res = await axios.post('ydd_cate/add', {
        catename,
        sort_num,
        icon
      })
      console.log(res);

      // console.log(document.querySelector('[name=alias]').value.length);
      if (document.querySelector('[name=alias]').value = '') return layer.msg('必填项不能为空')

      if (res.status === 200 && res.statusText === 'OK') {
        layer.msg('添加成功', {
          icon: 1,
          time: 2000,
        });
        render()
        layer.close(indexADdForm)
      }
    } catch (error) {
      // console.log(error)
      layer.msg('添加失败', {
        icon: 2,
        time: 2000 //2秒关闭（如果不配置，默认是3秒）
      })
    }

  }
  // 如果点击重置，清空表单数据
  else if (e.target.className === 'layui-btn layui-btn-primary') {
    form.reset()
  }

})


// todo ================= 删除分类功能 =================================
// 事件委托给list
document.querySelector('#list').addEventListener('click', function (e) {
  if (e.target.className === 'layui-btn layui-btn-danger layui-btn-xs btn_delete layui-icon layui-icon-delete wxy_del wxy_add_del') {
    // console.log(e.target.dataset.id);
    const id = e.target.dataset.id
    layer.confirm('您确定删除该分类吗', async function (index) {
      //do something
      const res = await axios.get('/ydd_cate/del', {
        params: {
          id
        }
      })
      // console.log(res.status);
      if (res.data.errno === 1000 && res.data.errmsg === '系统默认数据，不允许删除') {
        layer.msg(res.data.errmsg);
      } else {
        layer.msg('删除成功');
        render()
      }
      // 关闭提示框
      layer.close(index)
    });
  }
})

// todo ================= 修改分类功能 =================================
// 弹出模态框
const modification = `
          <form id="editForm" class="layui-form" lay-filter="editForm" style="padding-left: 40px;">
          <!-- 用来存id -->
          <div class="layui-form-item layui-hide">
            <label class="layui-form-label">分类名称</label>
            <div class="layui-input-block">
              <input type="text" name="id" readonly required lay-verify="required" placeholder="请输入标题" autocomplete="off"
                class="layui-input">
            </div>
          </div>
            <!-- 第一行 分类名称 -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类名称</label>
              <div class="layui-input-block">
                <input type="text" name="catename" required lay-verify="required" placeholder="请输入分类名" autocomplete="off"
                  class="layui-input wxy_fenlei" style="width: 80%;">
              </div>
            </div>
            <!-- 第二行 分类图标  -->
            <div class="layui-form-item">
              <label class="layui-form-label">分类图标</label>
              <div class="layui-input-block wxy_fot">
                <input type="text" name="icon" required lay-verify="required" placeholder="请输入class名" autocomplete="off"
                  class="layui-input" style="width: 40%;">
                  <i class="fa" id="icon" style="margin-left: 11px; margin-top: 14px;"></i>
                  <a href="https://fontawesome.com.cn/v4/icons-ui/" target="_blank">
                    <span style="display: inline-block;margin-left: 12px; margin-top: 12px;">具体参见fontawesome图标库</span>
                  </a>
              </div>
              
            </div>
            <!-- 第三行 -->
            <div class="layui-form-item">
              <label class="layui-form-label">排序大小</label>
              <div class="layui-input-block wxy_jiajian">
                <span class="wxy_jia j_j">+</span>
                <input type="text" name="sort_num" required lay-verify="required" placeholder="" autocomplete="off"
                  class="layui-input zj" style="width: 80%;">
                <span class="wxy_jian j_j">-</span>
            </div>
            <!-- 第四行 按钮 -->
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button class="layui-btn form_add change_btn" lay-submit lay-filter="formDemo">确认修改</button>
                <button type="reset" class="layui-btn layui-btn-primary reset_btn" id="form_reset">重置</button>
              </div>
            </div>
          </div>
          </form>
          `
let form = layui.form
let indexEditForm
// 事件委托给list
document.querySelector('#list').addEventListener('click', function (e) {
  if (e.target.className === 'layui-btn layui-btn-xs btn_edit layui-icon layui-icon-edit wxy_edit wxy_add_del') {
    const id = e.target.dataset.id
    console.log(id)


    // 发送ajax 获取数据
    gitUser(id)

    // todo======================== 修改 ======================================
    document.querySelector('body').addEventListener('click', async function (e) {

      // 处理input框
      document.querySelector('body').addEventListener('click', function (e) {
        let i = document.querySelector('[name=sort_num]')

        if (e.target.className === 'wxy_jia j_j') {
          i.value++
        } else if (e.target.className === 'wxy_jian j_j') {
          i.value--
          if (i.value <= 0) {
            i.value = 0
          }
        }
      })

      // 点击确认修改
      if (e.target.className === 'layui-btn form_add change_btn') {
        // console.log(data.id);
        // const data = $('#editForm').serialize()
        const data = serialize(editForm, { hash: true })
        console.log(data);
        const res = await axios.post('/ydd_cate/update', data)
        // console.log(res.status);
        if (res.status === 200 && res.statusText === 'OK') {
          layer.msg('已修改');
          render()
        } else {
          layer.msg('修改失败', { icon: 2 });
        }
        layer.close(indexEditForm)
      }
    })


    // 封装详情函数
    function gitUser(id) {
      axios.get(`/ydd_cate/rowInfo`, {
        params: {
          id
        }
      }).then(({ data: { data } }) => {
        // console.log(data)
        // console.log(data.icon);
        $('#icon').addClass(data.icon)
        const name = document.querySelectorAll('#editForm [name]')
        // console.log(name)
        name.forEach(item => {
          item.value = data[item.name]
        })
      })
    }
    // 点击重置
    document.querySelector('body').addEventListener('click', async function (e) {
      if (e.target.className === 'layui-btn layui-btn-primary reset_btn') {
        const id = document.querySelector('[name="id"]').value
        // console.log(id);
        gitUser(id)
      }
    })


    // 模态框
    indexEditForm = layer.open({
      content: modification,
      type: 1,
      title: ['修改分类', 'font-size:18px;'],
      area: ['684px', '347px']
    })
  }
})



// todo======================== 刷新 ======================================
document.querySelector('.shuaxing').addEventListener('click', function () {
  $('.refresh').click()
})

// todo======================== 查询 ======================================
document.querySelector('.wxy_input').addEventListener('change', async function () {

  query.catename = document.querySelector('.wxy_input').value
  render()


  document.querySelector('#reset').addEventListener('click', function () {
    document.querySelector('.wxy_input').value = ''
    $('.refresh').click()
  })
})

// todo======================== 分页器 ======================================
const laypage = layui.laypage;
function renderPage(total) {
  //执行一个laypage实例
  laypage.render({
    elem: 'page-box', //注意，这里的 test1 是 ID，不用加 # 号
    count: total, //数据总数，从服务端得到
    limit: query.limit, //设置每页多少条数据
    curr: query.page,
    limits: [5, 10, 15], //每页条数的选择项。
    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'], //排版
    jump: function (obj, first) {
      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数

      query.page = obj.curr
      query.limit = obj.limit

      //首次不执行
      if (!first) {
        //do something
        render()
      }
    }
  });
}



// 搜索框的显示和隐藏
let flag = true
$('.top_content').click(() => {
  flag ? $('.page-box').slideUp() : $('.page-box').slideDown()
  $('.top_content')[0].className = flag ? "layui-icon layui-icon-down top_content" : "layui-icon layui-icon-up top_content"
  flag = !flag
})

// 点击显示隐藏菜单
let flag1 = true
$('#pullDown').on('click', function (e) {
  e.stopPropagation()
  flag1 ? $('#menu').show() : $('#menu').hide()
  flag1 = !flag1
})
$('#menu').on('click', function (e) {
  e.stopPropagation()
  $('#menu').show()
})
// 点击页面让菜单消失
$('body').on('click', function () {
  $('#menu').hide()
  flag1 = true
})

// 点击隐藏列
$('body').on('change', '.cked', function () {
  // console.log(this.checked);
  // console.log($('#test [name="one"]'));
  this.checked ? $(`[name=${this.id}]`).show() : $(`[name=${this.id}]`).hide()
})





